package com.lemon.springcloud.core.listener.def;


import com.lemon.springcloud.core.listener.LemonBootStarterListener;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hdzhang
 * @ClassName LemonStarterListeners
 * @desc
 * @Date 2018/9/7 21:47
 * @Version 1.0
 **/
public class LemonStarterListeners {
    private static List<LemonBootStarterListener> listeners;

    LemonStarterListeners(List<LemonBootStarterListener> listeners) {
        if (LemonStarterListeners.listeners == null || LemonStarterListeners.listeners.size() == 0) {
            synchronized (LemonStarterListeners.class) {
                if (LemonStarterListeners.listeners == null || LemonStarterListeners.listeners.size() == 0) {
                    LemonStarterListeners.listeners = listeners;
                }
            }
        }
    }

    /**
     * onStarting
     */
    void onStarting() {
        for (LemonBootStarterListener listener : listeners) {
            listener.onStarting();
        }
    }

    /**
     * onPrepared
     *
     * @param context ApplicationContext
     */
    void onPrepared(ApplicationContext context) {
        if (!context.getId().contains("bootstrap")) {
            for (LemonBootStarterListener listener : listeners) {
                listener.onPrepared(context);
            }
        }
    }

    /**
     * onFinished
     *
     * @param context ApplicationContext
     */
    void onFinished(ApplicationContext context) {
        if (!context.getId().contains("bootstrap")) {
            for (LemonBootStarterListener listener : listeners) {
                listener.onFinished(context);
            }
        }
    }

    /**
     * Collect starter information.
     *
     * @return Starter information
     */
    public Map<String, Map<String, Object>> plugins() {
        Map<String, Map<String, Object>> plugins = new HashMap<String, Map<String, Object>>();
        int undefinedCnt = 0;
        for (LemonBootStarterListener listener : listeners) {
            String starterName = listener.starterName();
            if (StringUtils.isEmpty(starterName)) {
                continue;
            }
            plugins.put(StringUtils.isEmpty(starterName) ? "UNDEFINED_STARTER_NAME_" + (undefinedCnt++) : starterName,
                    listener.starterInfoCollect());
        }
        return plugins;
    }
}
